package stringoperation;

public class LongestSymmetricalLength {
  
  public static boolean isSymmetrical(String str){
    boolean s = true;
    int l = str.length();
    for(int i = 0; i < (l / 2); i++){
     if(str.charAt(i) != str.charAt(l - 1 - i)){
       s = false;
       break;
     }
    }
      
    return s;
  }
  
  //brute force
  public static int longestSymmetricalLength(String str){
    int sl = 0;
    if(str == null || str.length() < 2)
      return sl;
    int l = str.length();
    String ss = "";
    for(int i = 0; i < l-1; i++){
      for(int j = i+1; j < l;j++){
        if(isSymmetrical(str.substring(i, j+1))){
          int templ = str.substring(i, j+1).length();
          if(templ > sl){
            sl = templ;
            ss = str.substring(i, j+1);
          }
        }
      }
    }
    System.out.println(ss);
    return sl;
  }
  
  public static int longestSymmetricalLength2(String str){
    int sl = 0;
    if(str == null || str.length() < 2)
      return sl;
    int l = str.length();
    String ss = "";
    for(int i = 0; i < l; i++){
      int j = i-1; 
      int k = i+1;
      while(j >= 0 && k < l && str.charAt(j) == str.charAt(k)){
        j--;
        k++;
      }
      if(j >= 0 && k < l && k - j - 1 > sl){
        sl = k-j-1;
        ss = str.substring(j, k-1);
      }
      
      j = i; 
      k = i+1;
      while(j >= 0 && k < l && str.charAt(j) == str.charAt(k)){
        j--;
        k++;
      }
      if(j >= 0 && k < l && k - j - 1 > sl){
        sl = k-j-1;
        ss = str.substring(j, k-1);
      }
    }
    System.out.println(ss);
    return sl;
  }
  
  

  /**
   * @param args
   */
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println(longestSymmetricalLength2("fhdajkabbba"));
  }

}
